﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sugar.Enties;
using SqlSugar;
using Seating.utils;
namespace Seating
{
    public partial class Seating_Chose_Form : Form
    {

        private int libraryCloseHour = 22;

        public string LibraryId { get; set; }

        public Seating_Chose_Form(string libraryId)
        {
            InitializeComponent();
            this.LibraryId = libraryId;
        }


        private Button buildNewButton(string name, int line, int row, int width, ref Color color, ref Color bgColor, Font font, int seatingId)
        {
            Button btn = new Button();
            btn.Name = name + seatingId;
            btn.Text = seatingId.ToString();
            btn.ForeColor = color;
            btn.BackColor = bgColor;
            btn.Font = font;
            btn.Width = width;
            btn.Height = width;
            btn.Location = calcLocation(line, row, width, 0);

            btn.Click += (s, arg) =>
            {
                choseSeating(seatingId);
            };
            return btn;
        }


        private void choseSeating(int seatingId)
        {
            if (checkStudentNotLogin())
            {
                MessageBox.Show("登录预约座位");

                Form form = FormSigletonUtil.GeStudentLoginFormInstance();
                DialogResult result = form.ShowDialog();
                // 登录成功
                if (result == DialogResult.OK)
                {
                    reservationSeating(seatingId);
                }
                else if (result == DialogResult.Cancel)
                {
                    MessageBox.Show("用户取消");
                }
            }
            // 之前就登录过
            else
            {
                reservationSeating(seatingId);
            }


        }

        private void reservationSeating(int seatingId)
        {
            int startHour = comboBox_start.SelectedItem.ObjToInt();
            int hours = comboBox_hours.SelectedItem.ObjToInt();

            // 1. 判断该学生是否有未到期的座位
             Tb_ReservationManager db1 = new Tb_ReservationManager();
            SugarParameter paramStudentId = new SugarParameter("@StudentId", LoginUserUtil.CurrentStudent.StudentId);

            int notExpireCount = db1.Db.Ado.GetInt
             ("SELECT COUNT(*) FROM Tb_Reservation where StudentId=@StudentId and State<>0 and DATEADD(HOUR,Hours,ReservationTime)>GETDATE()", paramStudentId);
            if (notExpireCount >= 1) {
                MessageBox.Show("您有未到期的座位，无法预约");
                return;
            }
            

            // 2. 判断是否违约超过3次
            Tb_ReservationManager db = new Tb_ReservationManager();

            int count = db.Db.Ado.GetInt
             ("SELECT COUNT(*) FROM Tb_Reservation where State=9 and StudentId=@StudentId", paramStudentId);

            if (count >= 3)
            {
                MessageBox.Show("您的违约记录超过三次，无法预约");
                return;
            }
            Tb_Reservation reservation = new Tb_Reservation();
            reservation.StudentId = LoginUserUtil.CurrentStudent.StudentId;
            reservation.SeatingId = seatingId;
            reservation.State = 1;
            reservation.Hours = hours;
            reservation.ReservationTime = DateTime.Now.Date.AddHours(startHour);

            Tb_ReservationManager manager = new Tb_ReservationManager();
            manager.Insert(reservation);

            MessageBox.Show("预约成功");
        }
        private static Point calcLocation(int line, int row, int width, int space)
        {
            return new Point((line + 1) * width + (line - 1) * space, row * width + (row) * space);
        }
        private void Seating_Chose_Form_Load(object sender, EventArgs e)
        {
            fillStartTime();


        }

        private void fillStartTime()
        {
            // 从下个小时开始，到晚上闭馆（22点）前一小时
            int currentHour = DateTime.Now.ToString("HH").ObjToInt();
            int startHour = currentHour;
            if (startHour < 8) startHour = 8;

            for (int i = startHour; i < libraryCloseHour; i++)
            {
                comboBox_start.Items.Add(i);
            }


        }

        /// <summary>
        ///  查询空闲的座位
        /// </summary>
        private List<Tb_Seating> getFreeSeating(string LibraryId)
        {
            int startHour = comboBox_start.SelectedItem.ObjToInt();
            int hours = comboBox_hours.SelectedItem.ObjToInt();

            // 1. 查询时段内是否闭馆
            DateTime start = DateTime.Now.Date.AddHours(startHour);

            Tb_ReservationManager db1 = new Tb_ReservationManager();
            SugarParameter paramLibraryId = new SugarParameter("@LibraryId", LibraryId);
            SugarParameter paramStartTime = new SugarParameter("@startTime", start);

            int count = db1.Db.Ado.GetInt
             ("select COUNT(*) from Tb_LibraryCloseStrategy where LibraryId=@LibraryId and  ReopenTime>@startTime", paramLibraryId, paramStartTime);
            if (count >= 1)
            {
                // 闭馆
                MessageBox.Show("此段时间闭馆，请重新选择");
                return new List<Tb_Seating>();
            }
            // 2. 查询
            return new Tb_SeatingManager().getFreeSeating(LibraryId, startHour, hours);
        }
        private bool checkStudentNotLogin()
        {
            return LoginUserUtil.CurrentStudent == null || LoginUserUtil.CurrentStudent.StudentId == null;
        }

        private void button_query_Click(object sender, EventArgs e)
        {
            if (!checkFrontData())
            {
                MessageBox.Show("请选择正确数值");
                return;
            }
           

            panel_box.Controls.Clear();

            List<Tb_Seating> data = getFreeSeating(this.LibraryId);
            string name = "btn";
            int line = 0;
            int row = 0;
            int width = 49;

            Color color = Color.FromArgb(192, 192, 0);
            Color bgColor = Color.FromName("LightGreen");
            Font font = new Font("宋体", 15);

            int lineCount = 10;
            for (int num = 0; num < data.Count; num++)
            {
                row = num / lineCount;
                line = num % lineCount;

                Button btn = buildNewButton(name, line, row, width, ref color, ref bgColor, font, data[num].SeatingId);
                panel_box.Controls.Add(btn);

            }
        }

        private bool checkFrontData()
        {
            int startHour = comboBox_start.SelectedItem.ObjToInt();
            int hours = comboBox_hours.SelectedItem.ObjToInt();
            if (!(startHour >= 0 && hours > 0))
            {
                return false;
            }
            return true;
        }

        private void comboBox_start_SelectedValueChanged_1(object sender, EventArgs e)
        {
            comboBox_hours.Items.Clear();
            comboBox_hours.Text = "";

            int startHour = comboBox_start.SelectedItem.ObjToInt();
            for (int i = 1; i <= this.libraryCloseHour - startHour; i++)
            {
                comboBox_hours.Items.Add(i);
            }

        }


       
    }
}
